import { net } from 'electron'
import store from './store'
const $fetch = (url: string, defaultData: any) => {
    return new Promise((resolve) => {
        net.fetch(url).then((response: any) => {
            if (!response.ok) {
                resolve(defaultData)
                return
            }
            response.json().then((body: any) => {
                resolve(body)
            }).catch(() => {
                resolve(defaultData)
            })
        }).catch(() => {
            resolve(defaultData)
        })
    })
}

export const parseProject = (obj: any, info: any) => {
    let name = obj.name.split("/").pop();
    let screen = store.get(`projects.${name}.screen`)
    let fullscreen = store.get(`projects.${name}.fullscreen`, true);
    if (!screen) {
        let screenStr = obj.screen || "full"
        if (screenStr !== "full") {
            let size = screenStr.split("*")
            if (size.length === 2) {
                fullscreen = false;
                screen = { width: parseInt(size[0]), height: parseInt(size[1]) }
            }
        }
    }
    let language = obj.language || {}
    let locales: any = store.get('locales', {})
    for (let key in language) {
        if (!locales[key]) {
            locales[key] = {}
        }
        locales[key].keywords = Object.assign(locales[key].keywords || {}, language[key].keywords || [])
        delete language[key].keywords
        locales[key][name] = language[key]
    }
    store.set("locales", locales)
    let item = {
        name: name,
        version: obj.version,
        keywords: obj.keywords || [],
        fullscreen: fullscreen,
        screen: screen,
        mode: obj.mode,
    }
    item = Object.assign(item, info)
    store.set(`projects.${name}`, item)
    return item;
}

export const getProject = async (name: string, version: string, info: any) => {
    let current: any = store.get(`projects.${name}`)
    if (version && current && current.version === version) {
        current = Object.assign(current, info)
        current.upgradable = false
        store.set(`projects.${name}`, current)
        return current
    }
    let obj: any = {}
    try {
        obj = await $fetch(`https://registry.npmjs.org/@toy-kit/${name}/${version}`, {})
    } catch { }
    if (!obj.name) {
        return {}
    }
    let latest = parseProject(obj, info);
    if (current) {
        current.latest = latest
        current.upgradable = true
    } else {
        current = latest
        current.upgradable = false
    }
    store.set(`projects.${name}`, current)
    return current
}
export const getProjects = async () => {
    let items: any = []
    const data: any = await $fetch("https://registry.npmjs.org/-/v1/search?text=author:lufuhu&size=250", [])
    if (!data || data.length == 0) {
        return store.get("projects", [])
    }
    for (let i = 0; i < data.objects.length; i++) {
        let name = data.objects[i].package.name.split("/").pop();
        let item = await getProject(name, data.objects[i].package.version, {
            downloads: data.objects[i].downloads.monthly,
            updated: data.objects[i].updated,
        })
        if (item && item.name) {
            items.push(item)
        }
    }
    store.set("projects_update_at", new Date().getTime())
    return items;
}